package com.shunbo.convenient.controller;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.druid.support.json.JSONUtils;
import com.github.pagehelper.Page;
import com.shunbo.convenient.service.*;
import com.shunbo.convenient.utils.*;
import com.shunbo.convenient.vo.*;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.*;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.util.*;


import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/weChat")
public class WeChatController {


    @Resource
    private ProductService productService;
    @Resource
    private OrdersService ordersService;
    @Resource
    private ProductOrderService productOrderService;
    @Resource
    private BlessingService blessingService;
    @Resource
    private UserCouponService userCouponService;
    @Resource
    private CouponOrderService couponOrderService;
    @Resource
    private CouponService couponService;
    @Resource
    private StoreService storeService;

    private static String Key = "Vax1rYJUUES1tZwZtxJkS1G2qaEWf6ua";
    private static String appid = "wx1564032be1a4de0a";
    private static String mch_id = "1513059221";
    private static String ip = "47.104.16.212";

    /**
     * 商品下单
     *
     * @param orders
     * @return
     * @throws Exception
     */
    @RequestMapping("/toTakeWxProduct")
    @ResponseBody
    public ConvenientResult toTakeWx(@RequestBody Orders orders) throws Exception {
        orders.setCreateTime(DateUtils.getDate());
        orders.setTypeOrder("0");
        orders.setOrderId(LongUUidMananger.newAuthId() + "");
        ordersService.save(orders);
        ProductOrder productOrder = orders.getProductOrder().get(0);
        productOrder.setOid(orders.getId() + "");
        Product pro = productService.findById(productOrder.getPid() + "");
        Double money = (pro.getMoney() - orders.getCouponPrice());
        money = money / 100 * (100 + 5);
        money = oneAfterPoint(money) * 100;
        money = money * productOrder.getNum();
        String nonce_ste = LongUUidMananger.newAuthMenuId() + "";
        String out_trade_no = (LongUUidMananger.newChannelId() + 1) + "";
        SortedMap<Object, Object> map = new TreeMap<Object, Object>();
        map.put("appid", appid);
        map.put("body", "product");
        map.put("mch_id", mch_id);
        map.put("nonce_str", nonce_ste);
        map.put("notify_url", "http://" + ip + ":8080/weChat/toAppPrice?productOrderId=" + orders.getOrderId());
        map.put("out_trade_no", out_trade_no);
        map.put("spbill_create_ip", ip);
        map.put("total_fee", money.intValue());
        map.put("openid", orders.getUserId());
        map.put("trade_type", "JSAPI");
        String sign1 = createSign("UTF-8", map);
        String xml = "<xml><appid>" + appid + "</appid><body>product</body><mch_id>" + mch_id + "</mch_id><nonce_str>"
                + nonce_ste + "</nonce_str><notify_url>http://" + ip + ":8080/weChat/toAppPrice?productOrderId=" + orders.getOrderId() + "</notify_url><out_trade_no>"
                + out_trade_no + "</out_trade_no><spbill_create_ip>" + ip + "</spbill_create_ip><total_fee>" + money.intValue() + "</total_fee><openid>" + orders.getUserId() + "</openid><trade_type>JSAPI</trade_type><sign>" + sign1 + "</sign></xml>";

        String s = HttpClientUtil.doPostXml("https://api.mch.weixin.qq.com/pay/unifiedorder", xml);
        System.out.println(s);
        Document doc = DocumentHelper.parseText(s); // 将字符串转为XML
        Element rootElt = doc.getRootElement(); // 获取根节点
        String prepay_id = rootElt.elementTextTrim("prepay_id");
        System.out.println("prepay_id");
        productOrderService.save(productOrder);
        UserCoupon coupon = new UserCoupon();
        coupon.setId(Long.parseLong(orders.getCid()));
        coupon.setStatus(2);
        userCouponService.update(coupon);

        /**
         * java app微信支付接口
         */
        SortedMap<Object, Object> result = new TreeMap<Object, Object>();
        result.put("appId", appid);
        result.put("timeStamp", Long.toString(System.currentTimeMillis() / 1000));
        result.put("nonceStr", RandomStringUtils.randomAlphanumeric(32));
        result.put("package", "prepay_id=" + prepay_id);
        result.put("signType", "MD5");
        String sign = createSign("UTF-8", result);
        result.put("paySign", sign);
        result.put("orderId", orders.getOrderId());
        return ConvenientResult.build(200, "微信返回", result);
    }

    /**
     * 福袋下单
     *
     * @param orders
     * @return
     * @throws Exception
     */
    @RequestMapping("/toTakeWxBless")
    @ResponseBody
    public ConvenientResult toTakeWxBless(@RequestBody Orders orders) throws Exception {
        orders.setCreateTime(DateUtils.getDate());
        orders.setTypeOrder("1");
        orders.setOrderId(LongUUidMananger.newAuthId() + "");
        ordersService.save(orders);
        ProductOrder productOrder = orders.getProductOrder().get(0);
        productOrder.setOid(orders.getId() + "");
        Blessing pro = blessingService.findById(productOrder.getBid() + "");
        pro.setMoney(((pro.getMoney() - orders.getCouponPrice()) * 100) * productOrder.getNum());
        String nonce_ste = LongUUidMananger.newAuthMenuId() + "";
        String out_trade_no = (LongUUidMananger.newChannelId() + 1) + "";
        SortedMap<Object, Object> map = new TreeMap<Object, Object>();
        map.put("appid", appid);
        map.put("body", "product");
        map.put("mch_id", mch_id);
        map.put("nonce_str", nonce_ste);
        map.put("notify_url", "http://" + ip + ":8080/weChat/toAppPrice?blessingOrderId=" + orders.getOrderId());
        map.put("out_trade_no", out_trade_no);
        map.put("spbill_create_ip", ip);
        map.put("total_fee", pro.getMoney().intValue());
        map.put("openid", orders.getUserId());
        map.put("trade_type", "JSAPI");
        String sign1 = createSign("UTF-8", map);
        String xml = "<xml><appid>" + appid + "</appid><body>product</body><mch_id>" + mch_id + "</mch_id><nonce_str>"
                + nonce_ste + "</nonce_str><notify_url>http://" + ip + ":8080/weChat/toAppPrice?blessingOrderId=" + orders.getOrderId() + "</notify_url><out_trade_no>"
                + out_trade_no + "</out_trade_no><spbill_create_ip>" + ip + "</spbill_create_ip><total_fee>" + pro.getMoney().intValue() + "</total_fee><openid>" + orders.getUserId() + "</openid><trade_type>JSAPI</trade_type><sign>" + sign1 + "</sign></xml>";

        String s = HttpClientUtil.doPostXml("https://api.mch.weixin.qq.com/pay/unifiedorder", xml);
        System.out.println(s);
        Document doc = DocumentHelper.parseText(s); // 将字符串转为XML
        Element rootElt = doc.getRootElement(); // 获取根节点
        String prepay_id = rootElt.elementTextTrim("prepay_id");
        System.out.println("prepay_id");
        productOrderService.save(productOrder);
        if (!StringUtils.isEmpty(orders.getCid())) {
            UserCoupon coupon = new UserCoupon();
            coupon.setId(Long.parseLong(orders.getCid()));
            coupon.setStatus(1);
            userCouponService.update(coupon);
        }
        /**
         * java app微信支付接口
         */
        SortedMap<Object, Object> result = new TreeMap<Object, Object>();
        result.put("appId", appid);
        result.put("timeStamp", Long.toString(System.currentTimeMillis() / 1000));
        result.put("nonceStr", RandomStringUtils.randomAlphanumeric(32));
        result.put("package", "prepay_id=" + prepay_id);
        result.put("signType", "MD5");
        String sign = createSign("UTF-8", result);
        result.put("paySign", sign);
        result.put("orderId", orders.getOrderId());
        return ConvenientResult.build(200, "微信返回", result);
    }


    /**
     * 福袋下单
     *
     * @param orders
     * @return
     * @throws Exception
     */
    @RequestMapping("/toTakeWxBlessReset")
    @ResponseBody
    public ConvenientResult toTakeWxBlessReset(@RequestBody Orders orders) throws Exception {
        ProductOrder productOrder = orders.getProductOrder().get(0);
        Blessing pro = blessingService.findById(productOrder.getBid() + "");
        pro.setMoney(((pro.getMoney() - orders.getCouponPrice()) * 100) * productOrder.getNum());
        String nonce_ste = LongUUidMananger.newAuthMenuId() + "";
        String out_trade_no = (LongUUidMananger.newChannelId() + 1) + "";
        SortedMap<Object, Object> map = new TreeMap<>();
        map.put("appid", appid);
        map.put("body", "product");
        map.put("mch_id", mch_id);
        map.put("nonce_str", nonce_ste);
        map.put("notify_url", "http://" + ip + ":8080/weChat/toAppPrice?blessingOrderId=" + orders.getOrderId());
        map.put("out_trade_no", out_trade_no);
        map.put("spbill_create_ip", ip);
        map.put("total_fee", pro.getMoney().intValue());
        map.put("openid", orders.getUserId());
        map.put("trade_type", "JSAPI");
        String sign1 = createSign("UTF-8", map);
        String xml = "<xml><appid>" + appid + "</appid><body>product</body><mch_id>" + mch_id + "</mch_id><nonce_str>"
                + nonce_ste + "</nonce_str><notify_url>http://" + ip + ":8080/weChat/toAppPrice?blessingOrderId=" + orders.getOrderId() + "</notify_url><out_trade_no>"
                + out_trade_no + "</out_trade_no><spbill_create_ip>" + ip + "</spbill_create_ip><total_fee>" + pro.getMoney().intValue() + "</total_fee><openid>" + orders.getUserId() + "</openid><trade_type>JSAPI</trade_type><sign>" + sign1 + "</sign></xml>";

        String s = HttpClientUtil.doPostXml("https://api.mch.weixin.qq.com/pay/unifiedorder", xml);
        System.out.println(s);
        Document doc = DocumentHelper.parseText(s); // 将字符串转为XML
        Element rootElt = doc.getRootElement(); // 获取根节点
        String prepay_id = rootElt.elementTextTrim("prepay_id");
        System.out.println("prepay_id");
        if (!StringUtils.isEmpty(orders.getCid())) {
            UserCoupon coupon = new UserCoupon();
            coupon.setId(Long.parseLong(orders.getCid()));
            coupon.setStatus(1);
            userCouponService.update(coupon);
        }
        /**
         * java app微信支付接口
         */
        SortedMap<Object, Object> result = new TreeMap<Object, Object>();
        result.put("appId", appid);
        result.put("timeStamp", Long.toString(System.currentTimeMillis() / 1000));
        result.put("nonceStr", RandomStringUtils.randomAlphanumeric(32));
        result.put("package", "prepay_id=" + prepay_id);
        result.put("signType", "MD5");
        String sign = createSign("UTF-8", result);
        result.put("paySign", sign);
        result.put("orderId", orders.getOrderId());
        return ConvenientResult.build(200, "微信返回", result);
    }

    /**
     * 商品下单
     *
     * @param orders
     * @return
     * @throws Exception
     */
    @RequestMapping("/toTakeWxCar")
    @ResponseBody
    public ConvenientResult toTakeWxCar(@RequestBody Orders orders) throws Exception {
        orders.setCreateTime(DateUtils.getDate());
        orders.setTypeOrder("0");
        orders.setOrderId(LongUUidMananger.newAuthId() + "");
        ordersService.save(orders);
        List<ProductOrder> productOrder = orders.getProductOrder();
        Double money = 0.0;
        for (ProductOrder productOrders : productOrder
                ) {
            productOrders.setOid(orders.getId() + "");
            productOrderService.save(productOrders);
            Product pro = productService.findById(productOrders.getPid() + "");
            Double qian = pro.getMoney() / 100 * (100 + 5);
            qian = oneAfterPoint(qian) * 100;
            money += qian * productOrders.getNum();
        }
        if (orders.getCouponPrice() != null) {
            money = money - (orders.getCouponPrice() * 100);
        }
        String nonce_ste = LongUUidMananger.newAuthMenuId() + "";
        String out_trade_no = (LongUUidMananger.newChannelId() + 1) + "";
        SortedMap<Object, Object> map = new TreeMap<Object, Object>();
        map.put("appid", appid);
        map.put("body", "product");
        map.put("mch_id", mch_id);
        map.put("nonce_str", nonce_ste);
        map.put("notify_url", "http://" + ip + ":8080/weChat/toAppPrice?productCar_id=" + orders.getOrderId());
        map.put("out_trade_no", out_trade_no);
        map.put("spbill_create_ip", ip);
        map.put("total_fee", money.intValue());
        map.put("openid", orders.getUserId());
        map.put("trade_type", "JSAPI");
        String sign1 = createSign("UTF-8", map);
        String xml = "<xml><appid>" + appid + "</appid><body>product</body><mch_id>" + mch_id + "</mch_id><nonce_str>"
                + nonce_ste + "</nonce_str><notify_url>http://" + ip + ":8080/weChat/toAppPrice?productCar_id=" + orders.getOrderId() + "</notify_url><out_trade_no>"
                + out_trade_no + "</out_trade_no><spbill_create_ip>" + ip + "</spbill_create_ip><total_fee>" + money.intValue() + "</total_fee><openid>" + orders.getUserId() + "</openid><trade_type>JSAPI</trade_type><sign>" + sign1 + "</sign></xml>";

        String s = HttpClientUtil.doPostXml("https://api.mch.weixin.qq.com/pay/unifiedorder", xml);
        System.out.println(s);
        Document doc = DocumentHelper.parseText(s); // 将字符串转为XML
        Element rootElt = doc.getRootElement(); // 获取根节点
        String prepay_id = rootElt.elementTextTrim("prepay_id");
        System.out.println("prepay_id");

        if (!StringUtils.isEmpty(orders.getCid())) {
            UserCoupon coupon = new UserCoupon();
            coupon.setId(Long.parseLong(orders.getCid()));
            coupon.setStatus(1);
            userCouponService.update(coupon);
        }
        /**
         * java app微信支付接口
         */
        SortedMap<Object, Object> result = new TreeMap<Object, Object>();
        result.put("appId", appid);
        result.put("timeStamp", Long.toString(System.currentTimeMillis() / 1000));
        result.put("nonceStr", RandomStringUtils.randomAlphanumeric(32));
        result.put("package", "prepay_id=" + prepay_id);
        result.put("signType", "MD5");
        String sign = createSign("UTF-8", result);
        result.put("paySign", sign);
        result.put("orderId", orders.getOrderId());
        return ConvenientResult.build(200, "微信返回", result);
    }

    /**
     * 商品下单
     *
     * @param orders
     * @return
     * @throws Exception
     */
    @RequestMapping("/toTakeWxCarReset")
    @ResponseBody
    public ConvenientResult toTakeWxCarReset(@RequestBody Orders orders) throws Exception {
        List<ProductOrder> productOrder = orders.getProductOrder();
        Double money = 0.0;
        for (ProductOrder productOrders : productOrder
                ) {
            Product pro = productService.findById(productOrders.getPid() + "");
            Double qian = pro.getMoney() / 100 * (100 + 5);
            qian = oneAfterPoint(qian) * 100;
            money += qian * productOrders.getNum();
        }
        if (orders.getCouponPrice() != null) {
            money = money - (orders.getCouponPrice() * 100);
        }
        String nonce_ste = LongUUidMananger.newAuthMenuId() + "";
        String out_trade_no = (LongUUidMananger.newChannelId() + 1) + "";
        SortedMap<Object, Object> map = new TreeMap<Object, Object>();
        map.put("appid", appid);
        map.put("body", "product");
        map.put("mch_id", mch_id);
        map.put("nonce_str", nonce_ste);
        map.put("notify_url", "http://" + ip + ":8080/weChat/toAppPrice?productCar_id=" + orders.getOrderId());
        map.put("out_trade_no", out_trade_no);
        map.put("spbill_create_ip", ip);
        map.put("total_fee", money.intValue());
        map.put("openid", orders.getUserId());
        map.put("trade_type", "JSAPI");
        String sign1 = createSign("UTF-8", map);
        String xml = "<xml><appid>" + appid + "</appid><body>product</body><mch_id>" + mch_id + "</mch_id><nonce_str>"
                + nonce_ste + "</nonce_str><notify_url>http://" + ip + ":8080/weChat/toAppPrice?productCar_id=" + orders.getOrderId() + "</notify_url><out_trade_no>"
                + out_trade_no + "</out_trade_no><spbill_create_ip>" + ip + "</spbill_create_ip><total_fee>" + money.intValue() + "</total_fee><openid>" + orders.getUserId() + "</openid><trade_type>JSAPI</trade_type><sign>" + sign1 + "</sign></xml>";

        String s = HttpClientUtil.doPostXml("https://api.mch.weixin.qq.com/pay/unifiedorder", xml);
        System.out.println(s);
        Document doc = DocumentHelper.parseText(s); // 将字符串转为XML
        Element rootElt = doc.getRootElement(); // 获取根节点
        String prepay_id = rootElt.elementTextTrim("prepay_id");
        System.out.println("prepay_id");
        if (!StringUtils.isEmpty(orders.getCid())) {
            UserCoupon coupon = new UserCoupon();
            coupon.setId(Long.parseLong(orders.getCid()));
            coupon.setStatus(1);
            userCouponService.update(coupon);
        }
        /**
         * java app微信支付接口
         */
        SortedMap<Object, Object> result = new TreeMap<Object, Object>();
        result.put("appId", appid);
        result.put("timeStamp", Long.toString(System.currentTimeMillis() / 1000));
        result.put("nonceStr", RandomStringUtils.randomAlphanumeric(32));
        result.put("package", "prepay_id=" + prepay_id);
        result.put("signType", "MD5");
        String sign = createSign("UTF-8", result);
        result.put("paySign", sign);
        result.put("orderId", orders.getOrderId());
        return ConvenientResult.build(200, "微信返回", result);
    }

    /**
     * 代金券下单
     *
     * @param orders
     * @return
     * @throws Exception
     */
    @RequestMapping("/toTakeWxCoupon")
    @ResponseBody
    public ConvenientResult toTakeWxCoupon(@RequestBody CouponOrder orders) throws Exception {
        orders.setCreateTime(DateUtils.getDateTime());
        couponOrderService.save(orders);
        Coupon byId = couponService.findById(orders.getCid() + "");
        Double money = orders.getNum() * byId.getPrice() * 100;

        String nonce_ste = LongUUidMananger.newAuthMenuId() + "";
        String out_trade_no = (LongUUidMananger.newChannelId() + 1) + "";
        SortedMap<Object, Object> map = new TreeMap<Object, Object>();
        map.put("appid", appid);
        map.put("body", "coupon");
        map.put("mch_id", mch_id);
        map.put("nonce_str", nonce_ste);
        map.put("notify_url", "http://" + ip + ":8080/weChat/toAppPrice?coupon_id=" + orders.getId());
        map.put("out_trade_no", out_trade_no);
        map.put("spbill_create_ip", ip);
        map.put("total_fee", money.intValue());
        map.put("openid", orders.getUserId());
        map.put("trade_type", "JSAPI");
        String sign1 = createSign("UTF-8", map);
        String xml = "<xml><appid>" + appid + "</appid><body>coupon</body><mch_id>" + mch_id + "</mch_id><nonce_str>"
                + nonce_ste + "</nonce_str><notify_url>http://" + ip + ":8080/weChat/toAppPrice?coupon_id=" + orders.getId() + "</notify_url><out_trade_no>"
                + out_trade_no + "</out_trade_no><spbill_create_ip>" + ip + "</spbill_create_ip><total_fee>" + money.intValue() + "</total_fee><openid>" + orders.getUserId() + "</openid><trade_type>JSAPI</trade_type><sign>" + sign1 + "</sign></xml>";

        String s = HttpClientUtil.doPostXml("https://api.mch.weixin.qq.com/pay/unifiedorder", xml);
        System.out.println(s);
        Document doc = DocumentHelper.parseText(s); // 将字符串转为XML
        Element rootElt = doc.getRootElement(); // 获取根节点
        String prepay_id = rootElt.elementTextTrim("prepay_id");
        System.out.println("prepay_id");
        /**
         * java app微信支付接口
         */
        SortedMap<Object, Object> result = new TreeMap<Object, Object>();
        result.put("appId", appid);
        result.put("timeStamp", Long.toString(System.currentTimeMillis() / 1000));
        result.put("nonceStr", RandomStringUtils.randomAlphanumeric(32));
        result.put("package", "prepay_id=" + prepay_id);
        result.put("signType", "MD5");
        String sign = createSign("UTF-8", result);
        result.put("paySign", sign);
        return ConvenientResult.build(200, "微信返回", result);
    }

    //企业付款接口
    private static final String UNIFIEDORDER_URL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";

    @RequestMapping("/toTakeWzZz")
    @ResponseBody
    public ConvenientResult toTakeWzZz(String openId, String amount, String desc, String realName) throws Exception {
        String nonce_ste = LongUUidMananger.newAuthMenuId() + "";
        String partner_trade_no = (LongUUidMananger.newChannelId() + 3) + "";
        SortedMap<Object, Object> map = new TreeMap<Object, Object>();
        map.put("mch_appid", appid);
        map.put("mchid", mch_id);
        map.put("nonce_str", nonce_ste);
        map.put("partner_trade_no", partner_trade_no);
        map.put("openid", openId);
        map.put("check_name", "NO_CHECK");
        map.put("amount", amount);
        map.put("desc", desc);
        map.put("re_user_name", realName);
        map.put("spbill_create_ip", ip);
        String sign1 = createSign("UTF-8", map);
        String xml = "<xml><mch_appid>" + appid + "</mch_appid><mchid>" + mch_id + "</mchid><nonce_str>" + nonce_ste + "</nonce_str>" +
                "<partner_trade_no>" + partner_trade_no + "</partner_trade_no>" +
                "<openid>" + openId + "</openid>" +
                "<check_name>NO_CHECK</check_name>" +
                "<amount>" + amount + "</amount>" +
                "<desc>" + desc + "</desc>" +
                "<re_user_name>" + realName + "</re_user_name>" +
                "<spbill_create_ip>" + ip + "</spbill_create_ip>" +
                "<sign>" + sign1 + "</sign></xml>";
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        FileInputStream instream = new FileInputStream(new File("/home/cert/apiclient_cert.p12"));
        try {
            keyStore.load(instream, mch_id.toCharArray());
        } finally {
            instream.close();
        }
        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, mch_id.toCharArray())
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[]{"TLSv1"},
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        CloseableHttpResponse response = null;
        String resultString = "";
        HttpPost httpPost = new HttpPost(UNIFIEDORDER_URL);
        try {
            StringEntity entity = new StringEntity(xml, "utf-8");
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpclient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } finally {
            try {
                response.close();
                httpPost.releaseConnection();
                httpclient.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println(resultString);
        Document doc = DocumentHelper.parseText(resultString); // 将字符串转为XML
        Element rootElt = doc.getRootElement(); // 获取根节点
        String result_code = rootElt.elementTextTrim("result_code");
        System.out.println(result_code);
        if (result_code.equals("SUCCESS")) {
            return ConvenientResult.build(200, "调用成功", true);
        } else {
            return ConvenientResult.build(500, "调用失败", false);
        }
    }

    /**
     * 消息推送
     *
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping("/push")
    @ResponseBody
    public ConvenientResult push(String msg, String regId) {
        Store byId = storeService.findById(regId);
        if (byId == null || "1".equals(byId.getPushStatus())) {
            return ConvenientResult.build(200, "用户未开启推送", true);
        }
        // 设置好账号的app_key和masterSecret
        String appKey = "a845367392c1e532243ace7c";
        String masterSecret = "3633874021deda0cd633f849";
        //创建JPushClient(极光推送的实例)
        JPushClient jpushClient = new JPushClient(masterSecret, appKey);
        //推送的关键,构造一个payload
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.android())//指定android平台的用户
                .setAudience(Audience.alias(regId))//你项目中的用户标识
                .setNotification(Notification.android(msg, "订单推送", null))
                //发送内容,这里不要盲目复制粘贴,这里是我从controller层中拿过来的参数)
                .build();

        try {
            PushResult pu = jpushClient.sendPush(payload);
            int responseCode = pu.getResponseCode();
            return ConvenientResult.build(responseCode, "推送完成", true);
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
        return ConvenientResult.build(400, "发送失败", false);
    }


    @RequestMapping("/getminiqrQr")
    @ResponseBody
    public ConvenientResult getminiqrQr(String page, String width) {
        ResponseEntity<String> result = null;
        try {
            AccessToken accessToken1 = WeXinUtils.getAccessToken();
            Map<String, Object> params = new HashMap<>();
            params.put("page", page);
            params.put("scene", "test");
            params.put("width", width);
            CloseableHttpClient  httpClient = HttpClientBuilder.create().build();



            HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken1.getToken());

            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");

            String body = JsonUtils.objectToJson(params);

            StringEntity entity;

            entity = new StringEntity(body);

            entity.setContentType("image/png");



            httpPost.setEntity(entity);

            HttpResponse response;



            response = httpClient.execute(httpPost);

            InputStream inputStream = response.getEntity().getContent();
            try {
                String file = new Random().nextInt(99999999)+".png";
                String filePath = "/home/image/"+file;
                FileOutputStream out = new FileOutputStream(filePath);


                byte[] buffer = new byte[8192];

                int bytesRead = 0;

                while((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {

                    out.write(buffer, 0, bytesRead);

                }



                out.flush();

                out.close();
                return ConvenientResult.build(200, "生成成功", filePath);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (Exception e) {
            System.out.println("调用小程序生成微信永久二维码URL接口异常");
        }
        return ConvenientResult.build(200, "推送完成", result.getBody());
    }

    /**
     * 将二进制转换成文件保存
     *
     * @param instreams 二进制流
     * @param imgPath   图片的保存路径
     * @param imgName   图片的名称
     * @return 1：保存正常
     * 0：保存失败
     */
    public static int saveToImgByInputStream(InputStream instreams, String imgPath, String imgName) {
        int stateInt = 1;
        if (instreams != null) {
            try {
                File file = new File(imgPath, imgName);//可以是任何图片格式.jpg,.png等
                FileOutputStream fos = new FileOutputStream(file);
                byte[] b = new byte[1024];
                int nRead = 0;
                while ((nRead = instreams.read(b)) != -1) {
                    fos.write(b, 0, nRead);
                }
                fos.flush();
                fos.close();
            } catch (Exception e) {
                stateInt = 0;
                e.printStackTrace();
            } finally {
            }
        }
        return stateInt;
    }

    public static String createSign(String characterEncoding, SortedMap<Object, Object> parameters) {
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v)
                    && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + Key);
        System.out.println(sb.toString());
        String sign = MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }

    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname))
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes()));
            else
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes(charsetname)));
        } catch (Exception exception) {
        }
        return resultString;
    }

    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));

        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    public static double oneAfterPoint(double d) {

        String strD = String.valueOf(d * 10);
        String[] strArr = strD.split("\\.");

        return Double.parseDouble(strArr[0]) / 10;
    }


}

